use std::fs;
use anyhow::Result;
use csv::Reader;
use serde_json::{Value};
use crate::OutputFormat;


pub fn process_csv(input: &str, output: String, format: OutputFormat) -> Result<()> {
    let mut reader = Reader::from_path(input)?;
    let mut ret: Vec<Value> = Vec::with_capacity(128);
    let header = reader.headers()?.clone();
    for result in reader.records() {
        let record = result?;
        let json_value: Value = header.iter().zip(record.iter())
            .collect::<Value>();
        println!("{:?}", json_value);
        ret.push(json_value);
    }
    let content = match format {
        OutputFormat::Json => {
            serde_json::to_string_pretty(&ret)?
        }
        OutputFormat::Yaml => {
            serde_yaml::to_string(&ret)?
        }
        OutputFormat::Toml => {
            toml::to_string_pretty(&ret)?
        }
    };
    fs::write(output, content)?;
    Ok(())
}